//
//  CZEmoticonCell.swift
//  Weibo
//
//  Created by cc on 11/7/17.
//  Copyright © 2017 cc. All rights reserved.
//

import UIKit


/// 表情cell的协议
@objc protocol CZEmoticonCellDelegate: NSObjectProtocol {
    
    /// 表情cell选中表情模型
    ///
    /// - Parameter em: 表情模型，nil表示删除
    func emoticonCellDidSelectedEmoticon(cell:CZEmoticonCell, em: CZEmoticon?)
}

//表情的页面 cell
// - 每一个cell就是和collectionView 一样大小
// - 每一个cell中用九宫格的算法，自行添加 20个表情
// - 最后一个放置删除按钮
class CZEmoticonCell: UICollectionViewCell {
    
    //代理
    weak var delegate: CZEmoticonCellDelegate?
    
    //当前页面的表情模型，最多20个
    var emoticons: [CZEmoticon]? {
        didSet {
            //1.隐藏所有的按钮
            for v in contentView.subviews {
                v.isHidden = true
            }
            
            //显示删除按钮
            contentView.subviews.last?.isHidden = false
            
            //2. 遍历模型表情数组， 设置按钮图像
            for (i, em) in (emoticons ?? []).enumerated() {
                //1. 取出按钮
                if let btn = contentView.subviews[i] as? UIButton {
                    
                    //设置图像 - 如果图像为nil 会清空图像，避免利用
                    btn.setImage(em.image, for:[])
                    
                    //设置emoji 的字符串 -如果emoji为nil 会清空title，避免利用
                    btn.setTitle(em.emoji, for: [])
                    
                    btn.isHidden = false
                }
            }
        }
    }
    
    
    /// 表情选择提示视图
    private lazy var tipView = CZEmoticonTipView()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("something wrong")
    }
    
    
    override func awakeFromNib() {
        setupUI()
    }
    
    //当视图从界面上删除，同样会调用此方法， newWindow == nil
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        
        guard let w = newWindow else {
            return
        }
        
        //将提示视图添加到窗口上
        w.addSubview(tipView)
        tipView.isHidden = true
        
    }
    
    
    
    //MARK: -监听方法
    ///选中表情按钮
    @objc private func selectedEmoticonButton(button: UIButton) {
        //1.取tag 0-20, 20对应的是删除按钮
        let tag = button.tag
        
        //2. 根据tag判断是否是删除按钮,如果不是删除按钮，取得表情
        var em: CZEmoticon?
        if tag < (emoticons?.count)! {
            em = emoticons?[tag]
        }
        
        //3. em 要么是选中的模型， 如果为nil 对应的是删除按钮
        delegate?.emoticonCellDidSelectedEmoticon(cell: self, em: em)
        
    }
    
    
    /// 长按手势识别
    @objc private func longGesture(gesture: UILongPressGestureRecognizer) {
        //addSubview(tipView)
        //1>获取触摸的位置
        let location = gesture.location(in: self)
        
        //2> 获取触摸位置对应的按钮
        guard let button = buttonWithLocation(location: location) else {
            tipView.isHidden = true
            return
        }
        
        //3> 处理手势状态
        switch gesture.state {
        case .began, .changed:
            tipView.isHidden = false
            
            //坐标系的转换 -> 将按钮参照cell的坐标系，转换到window的坐标位置
            let center = self.convert(button.center, to: window)
            
            //设置提示视图的位置
            tipView.center = center
            
            //设置提示视图的表情模型
            if button.tag < (emoticons?.count)! {
                tipView.emoticon = emoticons?[button.tag]
            }
        case .ended:
            tipView.isHidden = true
            selectedEmoticonButton(button: button)
        case .cancelled, .failed:
            tipView.isHidden = true
            
        default:
            break
        }

    }
    
    
    private func buttonWithLocation(location: CGPoint) -> UIButton? {
        //遍历contentView 所有的子视图， 如果可见，同时在location上，就是按钮
        for btn in contentView.subviews as! [UIButton] {
            
            //删除按钮同样需要处理
            if btn.frame.contains(location) && !btn.isHidden && btn != contentView.subviews.last{
                return btn
            }
        }
        return nil
    }
    
}

//MARK : -设置界面
private extension CZEmoticonCell {
    
    
    // 从XIB加载， bounds是xib中定义的大小，不是size的大小
    // 纯代码创建，bounds 就是布局属性中创建的itemSize
    func setupUI() {
        
        let rowCount = 3
        let colCount = 7
        //左右间隔
        let leftMargin: CGFloat = 8
        //底部间隔，为分页控件预留空间
        let bottomMargin: CGFloat = 48
        
        let w = (bounds.width - 2 * leftMargin) / CGFloat(colCount)
        let h = (bounds.height - bottomMargin) / CGFloat(rowCount)
        
        //连续创建21个按钮
        for i in 0..<21 {
            let row = i / colCount
            let col = i % colCount
            let btn = UIButton()
            //设置按钮的大小
            let x = leftMargin + CGFloat(col) * w
            let y = CGFloat(row) * h
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            contentView.addSubview(btn)
            
            //设置按钮的字体大小
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            
            //设置按钮的tag
            btn.tag = i
            //添加监听方法
            btn.addTarget(self, action: #selector(selectedEmoticonButton), for:.touchUpInside)
            
            
        }
        
        //取出末尾的删除按钮
        let removeButton = contentView.subviews.last as! UIButton
        //设置图像
        let image = UIImage(named: "compose_emotion_delete", in: CZEmoticonManager.shared.bundle, compatibleWith: nil)
        removeButton.setImage(image, for: [])
        
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longGesture))
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
        
    }
    
}

